package com.xbao.opensearch.controller.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by qingshengzheng on 2019/1/7.
 */
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.hd.agr.service.search")
public class ElasticSearchConfig {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);

    @Value("${es.hostName}")
    private String hostName = "192.168.1.150";

    @Value("${es.transport}")
    private Integer transport = 9301;

    @Value("${es.cluster.name}")
    private String clusterName = "search_2";

    @Bean
    public TransportClient transportClient() {

        TransportClient transportClient = null;

        try {
            String[] hostNames = getHostNames(hostName);

            //配置信息
            Settings es = Settings.builder().put("cluster.name", clusterName).build();

            //配置信息Settings自定义
            transportClient = new PreBuiltTransportClient(es);

            for (String tempHostNames : hostNames) {
                TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(tempHostNames), transport);
                transportClient.addTransportAddress(transportAddress);
            }
        } catch (UnknownHostException e) {
            logger.error("ES创建错误", e);
        }
        return transportClient;
    }

    //获取集群hostName apollo中使用,隔离开的
    private String[] getHostNames(String hostNames) {
        return hostNames.split(",");
    }
}
